package com.yd.mvc.baseController;

import com.yd.app.util.BusinessException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zg
 * 组织机构增删改查
 */
@Controller
public class UploadController extends BaseController {

    @Value("${base.img.url}")
    private String base_img_url;
    @ResponseBody
    @RequestMapping(value = "/dapi/upload/file", method = RequestMethod.POST)
    public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url= base_img_url;
        request.setCharacterEncoding("utf-8");
        uploadFile(url,request);
    }
    //上传图片到  img_url
    @ResponseBody
    @RequestMapping(value = "/dapi/upload/link", method = RequestMethod.POST)
    public String uploadLink(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String str_url="link";
        String url=getImg_urlAndUpload(str_url,request);
        return url;
    }

    /**
     * 上传图片到指定目录
     * @param str_url
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/dapi/upload/image/{str_url}", method = RequestMethod.POST)
    public String uploadImageToUrl(@PathVariable("str_url")String str_url, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url=getImg_urlAndUpload(str_url,request);
        return url;
    }
    //上传并返回路径
    public String getImg_urlAndUpload(String str_url,HttpServletRequest request) throws Exception {
        String url= base_img_url+str_url;
        request.setCharacterEncoding("utf-8");
        String iss= uploadFile(url,request);
        return str_url+"/"+iss;
    }
    //上传图片到  img_url
    @ResponseBody
    @RequestMapping(value = "/dapi/upload", method = RequestMethod.POST)
    public String uploadPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url=getImg_url(request);
        return url;
    }
    //上传图片到  img_url
    @ResponseBody
    @RequestMapping(value = "/dapi/upload/zs", method = RequestMethod.POST)
    public String uploadPicZs(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url=getImg_url_ZS(request);
        return url;
    }
    //上传并返回路径
    public String getImg_url_ZS(HttpServletRequest request) throws Exception {
        String url= base_img_url+"ZS";
        request.setCharacterEncoding("utf-8");
        String iss= uploadFile(url,request);
        return "ZS/"+iss;
    }
    //上传并返回路径
    public String getImg_url(HttpServletRequest request) throws Exception {
        String url= base_img_url;
        request.setCharacterEncoding("utf-8");
        String iss= uploadFile(url,request);
        return iss;
    }
    //上传文件返回路径
    @ResponseBody
    @RequestMapping(value = "/dapi/upload/attachment", produces = { "application/json" }, method = RequestMethod.POST)
    public String  importAttachment(HttpServletRequest request) throws Exception {
        String url = "";
        try{
            url = uploadFile(base_img_url,request);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(500,"上传失败");
        }
        return url;
    }
    /**
     * @Author: zy
     * @Desc: 旧物回收
     * @Date:  2018/4/12
     * @Param
     */
    @ResponseBody
    @RequestMapping(value = "/dapi/upload/old", method = RequestMethod.POST)
    public String uploadOld(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String str_url="old";
        String url=getImg_urlAndUpload(str_url,request);
        return url;
    }

    protected String uploadFile(String url, HttpServletRequest request) throws Exception {
        // 上传文件存放路径
        request.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        String fileurl="";
        String fileNames="";
        String file_dirs_url=url;//文件夹路径
        File makedirs=new File(file_dirs_url);
        if(!makedirs.exists()){
            makedirs.mkdirs();
        }
        File saveFile=null;
        try {
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String dateStr=new Date().getTime()+"_";
                String fieldName="";
                if (!item.isFormField()) {
                    //获取路径名
                    String value = item.getName() ;
                    //索引到最后一个反斜杠
                    int start = value.lastIndexOf("\\");
                    //截取 上传文件的 字符串名字，加1是 去掉反斜杠
                   /* int num=value.indexOf(".");
                   int leng= value.length();*/
                   // value=value.substring(value.indexOf("."),value.length());
                  // fieldName = value.substring(start+1);
                    fieldName = value;
                    fileurl=file_dirs_url+"/"+dateStr+fieldName;
                    saveFile = new File(fileurl);
                    item.write(saveFile); // 写入file，指向一个具体的文件
                    fileNames+=dateStr+fieldName+",";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        if(fileNames.equals("")){
            return "";
        }
        return fileNames.substring(0,fileNames.length()-1);
    }











   /* @ResponseBody
    @RequestMapping(value = "/config")
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception{
        try {
            System.out.println("上传图片=======================");
           // response.setContentType("application/json");
            request.setCharacterEncoding( "utf-8" );
            response.setHeader("Content-Type" , "text/html");
            String rootPrth=request.getSession().getServletContext().getRealPath("/");
            System.out.println(rootPrth);
            rootPrth=rootPrth+"WEB-INF\\classes\\config.json";
            String exec=new ActionEnter(request,rootPrth).exec();
            PrintWriter writer=response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ResponseBody
    @RequestMapping(value = "/uploadimage")
    public String uploadimage(HttpServletRequest request) throws Exception{
        System.out.println("上传图片===============sss========");
        return "succccc";
    }*/

}
